<?php

Raise::load('core.RaiseObject');
Raise::load('core.IRaiseSessionStore');
Raise::load('core.RaisePath');
Raise::load('core.RaiseFile');
Raise::load('core.RaiseFileSystem');
Raise::load('core.RaiseHashDigest');

/**
 * RaiseSessionFileStore class
 * file storage for session store
 *
 * @author Sam-Mauris Yong <hellclanner at live dot com>
 * @license http://www.opensource.org/licenses/bsd-license New BSD License
 * @package Raise.Core.Session.Store
 * @since 1.2
 */
class RaiseSessionFileStore extends RaiseObject implements IRaiseSessionStore {

    /**
     * The path name to the folder containing all the RaiseSession storage
     * @var string
     */
    private $folder;

    /**
     * The session name
     * @var string
     */
    private $sessionName;

    /**
     * Create a new RaiseSessionFileStore
     * @param string $folder The folder to store all the session data
     */
    public function  __construct($folder) {
        $this->folder = $folder;
    }

    public function close() {
        return true;
    }

    public function destroy($sessionId) {
        $path = RaisePath::combine($this->folder, $this->sessionName . '-' . $sessionId);
        $file = new RaiseFile($path);
        if($file->exists()){
            return $file->delete();
        }
    }

    public function garbageCollect($life) {
        $files = RaiseFileSystem::pathSearch(RaisePath::combine($this->folder, $this->sessionName . '-*'));
        foreach($files as $f){
            $file = new RaiseFile($f);
            if($file->getLastModified()->add(new RaiseTimeSpan($life))->toTimestamp() < time()){
                $file->delete();
            }
        }
    }

    public function open($path, $sessionName) {
        $this->sessionName = RaiseHashDigest::crc32($sessionName);
        return true;
    }

    public function read($sessionId) {
        $path = RaisePath::combine($this->folder, $this->sessionName . '-' . $sessionId);
        $file = new RaiseFile($path);
        if($file->exists()){
            return $file->getContent();
        }
        return '';
    }

    public function write($sessionId, $data) {
        $path = RaisePath::combine($this->folder, $this->sessionName . '-' . $sessionId);
        $file = new RaiseFile($path);
        $ok = false;
        if($file->exists()){
            $ok = $file->setContent($data);
        }else{
            RaiseFileSystem::createFile($path, $data);
            $ok = true;
        }

        return $ok;
    }

    public function sessionExist($sessionId) {
        $path = RaisePath::combine($this->folder, $this->sessionName . '-' . $sessionId);
        $file = new RaiseFile($path);
        return $file->exists();
    }

}
